package com.redxun.interceptor;

import com.redxun.core.api.org.ICoreUserService;
import com.redxun.core.common.entity.JsonResult;
import com.redxun.core.common.model.ReturnT;
import com.redxun.core.dto.user.OsUserDto;
import com.xxl.job.admin.controller.annotation.PermissionLimit;
import com.xxl.job.admin.core.model.XxlJobUser;
import com.xxl.job.admin.core.util.I18nUtil;
import com.xxl.job.admin.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限拦截.
 *
 * @author xuxueli 2015-12-12 18:09:04
 */
@Component
public class PermissionInterceptor extends HandlerInterceptorAdapter {

	@Autowired
	private LoginService loginService;
	
	@Autowired
	private ICoreUserService userService;


	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		
		if (!(handler instanceof HandlerMethod)) {
			return super.preHandle(request, response, handler);
		}

		// if need login
		boolean needLogin = true;
		boolean needAdminuser = false;
		HandlerMethod method = (HandlerMethod)handler;
		PermissionLimit permission = method.getMethodAnnotation(PermissionLimit.class);
		if (permission != null) {
			needLogin = permission.limit();
			needAdminuser = permission.adminuser();
		}

		if (needLogin) {

			XxlJobUser loginUser = loginService.ifLogin(request, response);
			if (loginUser == null) {
				String authorization = request.getParameter("authorization");
				JsonResult<OsUserDto> jsonResult= userService.getLoginUserInfoByToken(authorization);
				if (jsonResult  !=  null && jsonResult.getData()  !=  null) {
					OsUserDto user = jsonResult.getData();
					ReturnT returnT = loginService.login(request, response, user, user.getFullName(), user.getPassword(), true,true);
					loginUser = (XxlJobUser) returnT.getContent();
				}
			}
			if (needAdminuser && loginUser.getRole() != 1) {
				throw new RuntimeException(I18nUtil.getString("system_permission_limit"));
			}
			request.setAttribute(LoginService.LOGIN_IDENTITY_KEY, loginUser);
		}

		return super.preHandle(request, response, handler);
	}
	
}
